<?php
/*
Plugin Name: WordPress Cloud Upload
Plugin URI: https://api.dwo.cc
Description: 用于将WordPress媒体文件上传到云端存储的插件
Version: 1.6.11
Author: 小渡API
Author URI: https://api.dwo.cc
License: Apache License 2.0
License URI: http://www.apache.org/licenses/LICENSE-2.0
Text Domain: wordpress-cloud-upload
Domain Path: /languages
*/

/**
 * @package WordPressCloudUpload
 * @author 小渡API
 * @version 1.6.11
 * @link https://api.dwo.cc
 * 
 * Copyright 2025 小渡API
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

if (!defined('ABSPATH')) exit;

// 注册设置
add_action('admin_init', 'suna_register_settings');
function suna_register_settings() {
    register_setting('suna_options_group', 'suna_aid');
    register_setting('suna_options_group', 'suna_key');
    register_setting('suna_options_group', 'suna_fid'); // 文件夹ID设置
    register_setting('suna_options_group', 'suna_api_url', 'suna_sanitize_api_url'); // API地址设置
    register_setting('suna_options_group', 'suna_button_position', 'suna_sanitize_button_position'); // 按钮位置设置
    register_setting('suna_options_group', 'suna_force_all_uploads', 'suna_sanitize_boolean'); // 强制所有上传走云存储
    
    add_settings_section(
        'suna_api_section',
        '速纳云盘API设置',
        'suna_api_section_callback',
        'suna-settings'
    );
    
    add_settings_field(
        'suna_aid',
        'AID',
        'suna_aid_field_callback',
        'suna-settings',
        'suna_api_section'
    );
    
    add_settings_field(
        'suna_key',
        'API Key',
        'suna_key_field_callback',
        'suna-settings',
        'suna_api_section'
    );
    
    add_settings_field(
        'suna_fid',
        '默认文件夹ID',
        'suna_fid_field_callback',
        'suna-settings',
        'suna_api_section'
    );
    
    add_settings_field(
        'suna_api_url',
        'API基础地址',
        'suna_api_url_field_callback',
        'suna-settings',
        'suna_api_section'
    );
    
    add_settings_field(
        'suna_button_position',
        '上传按钮位置',
        'suna_button_position_field_callback',
        'suna-settings',
        'suna_api_section'
    );
    
    add_settings_field(
        'suna_force_all_uploads',
        '强制所有上传',
        'suna_force_all_uploads_field_callback',
        'suna-settings',
        'suna_api_section'
    );
}

// 验证布尔值设置
function suna_sanitize_boolean($input) {
    return $input === 'on' ? 'on' : 'off';
}

// 验证API地址
function suna_sanitize_api_url($input) {
    if (empty($input)) {
        return 'https://api.snpan.com/opapi';
    }
    return rtrim($input, '/');
}

// 验证按钮位置设置
function suna_sanitize_button_position($input) {
    $valid_positions = ['default', 'top_right', 'bottom_right', 'top_left'];
    return in_array($input, $valid_positions) ? $input : 'default';
}

function suna_api_section_callback() {
    echo '<p>请输入您的速纳云盘API信息，完成配置后即可使用速纳云盘上传功能</p>';
}

function suna_aid_field_callback() {
    $aid = get_option('suna_aid');
    echo '<input type="text" name="suna_aid" value="' . esc_attr($aid) . '" class="regular-text">';
    echo '<p class="description">请在速纳云盘账户中获取您的AID</p>';
}

function suna_key_field_callback() {
    $key = get_option('suna_key');
    echo '<input type="text" name="suna_key" value="' . esc_attr($key) . '" class="regular-text">';
    echo '<p class="description">请在速纳云盘账户中获取您的API Key</p>';
}

function suna_fid_field_callback() {
    $fid = get_option('suna_fid');
    echo '<input type="text" name="suna_fid" value="' . esc_attr($fid) . '" class="regular-text" placeholder="可选，留空则上传到根目录">';
}

function suna_api_url_field_callback() {
    $api_url = get_option('suna_api_url', 'https://api.snpan.com/opapi');
    echo '<input type="text" name="suna_api_url" value="' . esc_attr($api_url) . '" class="regular-text" placeholder="默认: https://api.snpan.com/opapi">';
    echo '<p class="description">API服务的基础地址，一般无需修改</p>';
}

function suna_button_position_field_callback() {
    $position = get_option('suna_button_position', 'default');
    echo '<select name="suna_button_position" class="regular-text">';
    echo '<option value="default"' . selected($position, 'default', false) . '>默认位置（整合到上传区域）</option>';
    echo '<option value="top_right"' . selected($position, 'top_right', false) . '>右上角悬浮</option>';
    echo '<option value="bottom_right"' . selected($position, 'bottom_right', false) . '>右下角悬浮</option>';
    echo '<option value="top_left"' . selected($position, 'top_left', false) . '>左上角悬浮</option>';
    echo '</select>';
    echo '<p class="description">选择速纳云盘上传按钮的显示位置</p>';
}

function suna_force_all_uploads_field_callback() {
    $force = get_option('suna_force_all_uploads', 'on');
    echo '<label>';
    echo '<input type="checkbox" name="suna_force_all_uploads" ' . checked($force, 'on', false) . '> ';
    echo '强制所有文件上传都通过速纳云盘（包括主题和其他插件的上传）';
    echo '</label>';
    echo '<p class="description">启用此选项后，所有上传请求将被速纳云盘接管</p>';
}

// 添加设置菜单
add_action('admin_menu', 'suna_add_admin_menu');
function suna_add_admin_menu() {
    add_options_page(
        '速纳云盘设置',
        '速纳云盘',
        'manage_options',
        'suna-settings',
        'suna_options_page'
    );
}

function suna_options_page() {
    $aid = get_option('suna_aid');
    $key = get_option('suna_key');
    ?>
    <div class="wrap">
        <h1>速纳云盘设置</h1>
        <?php if (empty($aid) || empty($key)): ?>
            <div class="notice notice-warning">
                <p>⚠️ 请先配置AID和API Key，否则无法使用云上传功能</p>
            </div>
        <?php endif; ?>
        <form action="options.php" method="post">
            <?php
            settings_fields('suna_options_group');
            do_settings_sections('suna-settings');
            submit_button();
            ?>
        </form>
    </div>
    <?php
}

// 添加版权信息通知
add_action('admin_footer', 'suna_show_copyright_notice');
function suna_show_copyright_notice() {
    $copyrightInfo = "速纳云盘上传插件\n\n版本：1.6.11\n作者：小渡API\n官网：https://api.dwo.cc\n\n注意：本插件完全免费使用！\n请勿用于任何商业用途的非法传播。\n\n感谢您的支持！";
    
    echo '<script>
    document.addEventListener("DOMContentLoaded", function() {
        // 检查是否已经显示过版权信息
        if (!localStorage.getItem("suna_copyright_shown")) {
            // 创建通知元素
            var noticeDiv = document.createElement("div");
            noticeDiv.innerHTML = "' . str_replace("\n", "<br>", $copyrightInfo) . '";
            noticeDiv.style.cssText = "position:fixed;top:20px;right:20px;padding:15px;background:#fff;border:1px solid #ccc;box-shadow:0 2px 10px rgba(0,0,0,0.1);z-index:10000;border-radius:5px;font-size:14px;max-width:300px;";
            
            // 添加关闭按钮
            var closeBtn = document.createElement("button");
            closeBtn.innerHTML = "×";
            closeBtn.style.cssText = "position:absolute;top:5px;right:5px;background:none;border:none;font-size:18px;font-weight:bold;cursor:pointer;";
            closeBtn.onclick = function() { document.body.removeChild(noticeDiv); };
            noticeDiv.appendChild(closeBtn);
            
            // 显示通知
            document.body.appendChild(noticeDiv);
            localStorage.setItem("suna_copyright_shown", "true");
            
            // 10秒后自动隐藏
            setTimeout(function() { 
                if (document.body.contains(noticeDiv)) {
                    document.body.removeChild(noticeDiv);
                }
            }, 10000);
        }
    });
    </script>';
}

// 加载样式和脚本
add_action('admin_enqueue_scripts', 'suna_enqueue_scripts', 999);
function suna_enqueue_scripts() {
    $screen = get_current_screen();
    $valid_screens = [
        'upload', 'media', 'post', 'page', 'edit-post', 'edit-page', 
        'media-library', 'post-new', 'page-new', 'customize', 'widgets'
    ];
    
    // 对所有管理页面加载脚本，确保全覆盖
    if (!$screen || (isset($screen->base) && $screen->base !== 'toplevel_page_suna-settings')) {
        // 获取按钮位置设置
        $button_position = get_option('suna_button_position', 'default');
        
        // 悬浮按钮位置样式
        $floating_positions = [
            'top_right' => 'top: 20px; right: 20px;',
            'bottom_right' => 'bottom: 20px; right: 20px;',
            'top_left' => 'top: 20px; left: 20px;'
        ];
        
        $floating_style = '';
        if (isset($floating_positions[$button_position])) {
            $floating_style = $floating_positions[$button_position];
        }
        
        // 修改CSS，优化按钮样式和整体UI
        wp_add_inline_style('wp-admin', '
            #suna-upload-btn, #suna-upload-btn-editor { 
                display: inline-flex !important; 
                align-items: center;
                background: #2c3e50 !important;
                color: white !important;
                border-color: #1a252f !important;
                padding: 6px 16px;
                text-decoration: none;
                font-size: 14px;
                font-weight: 500;
                line-height: 26px;
                height: 38px;
                margin: 0 10px 0 0 !important;
                cursor: pointer;
                border-width: 1px;
                border-style: solid;
                border-radius: 6px;
                white-space: nowrap;
                box-sizing: border-box;
                transition: all 0.2s ease;
                box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            }
            
            /* 悬浮按钮特殊样式 */
            .suna-floating-btn {
                position: fixed !important;
                z-index: 9999 !important;
                width: 56px !important;
                height: 56px !important;
                border-radius: 50% !important;
                padding: 0 !important;
                margin: 0 !important;
                box-shadow: 0 4px 12px rgba(44, 62, 80, 0.3) !important;
                justify-content: center !important;
                transform: translateZ(0);
                overflow: hidden;
            }
            
            .suna-floating-btn::before {
                content: "";
                position: absolute;
                top: 50%;
                left: 50%;
                width: 120%;
                height: 120%;
                background: rgba(255, 255, 255, 0.1);
                transform: translate(-50%, -50%) rotate(45deg) scale(0);
                transition: transform 0.5s ease;
            }
            
            .suna-floating-btn:hover::before {
                transform: translate(-50%, -50%) rotate(45deg) scale(1);
            }
            
            .suna-floating-btn .dashicons {
                margin-right: 0 !important;
                font-size: 24px !important;
            }
            
            .suna-floating-btn.top-right { ' . $floating_positions['top_right'] . ' }
            .suna-floating-btn.bottom-right { ' . $floating_positions['bottom_right'] . ' }
            .suna-floating-btn.top-left { ' . $floating_positions['top_left'] . ' }
            
            #suna-upload-btn:hover, #suna-upload-btn-editor:hover {
                background: #34495e !important;
                color: white !important;
                transform: translateY(-1px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            }
            
            #suna-upload-btn:active, #suna-upload-btn-editor:active {
                transform: translateY(0);
                box-shadow: 0 2px 3px rgba(0,0,0,0.1);
            }
            
            #suna-upload-btn .dashicons, #suna-upload-btn-editor .dashicons {
                margin-right: 6px;
                font-size: 18px;
            }
            
            .suna-modal { 
                display: none; 
                position: fixed; 
                top: 0; 
                left: 0; 
                width: 100%; 
                height: 100%; 
                background: rgba(0,0,0,0.7); 
                z-index: 99999; 
                overflow-y: auto;
                animation: fadeIn 0.3s ease;
            }
            
            @keyframes fadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
            }
            
            .suna-modal-content { 
                position: absolute; 
                top: 50%; 
                left: 50%; 
                transform: translate(-50%, -50%); 
                background: white; 
                padding: 25px; 
                border-radius: 8px; 
                width: 550px; 
                max-width: 90%; 
                box-shadow: 0 10px 30px rgba(0,0,0,0.2);
                animation: slideIn 0.3s ease;
            }
            
            @keyframes slideIn {
                from { transform: translate(-50%, -60%); opacity: 0; }
                to { transform: translate(-50%, -50%); opacity: 1; }
            }
            
            .suna-close { 
                float: right; 
                cursor: pointer; 
                font-size: 24px; 
                line-height: 1;
                padding: 5px;
                color: #777;
                transition: color 0.2s;
            }
            
            .suna-close:hover {
                color: #333;
            }
            
            .suna-progress { 
                display: none; 
                margin-top: 15px; 
            }
            
            .suna-progress-bar { 
                height: 8px; 
                background: #eee; 
                border-radius: 4px; 
                overflow: hidden; 
                box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
            }
            
            .suna-progress-fill { 
                height: 100%; 
                background: #3498db; 
                width: 0%; 
                transition: width 0.3s ease; 
            }
            
            .suna-message { 
                margin-top: 15px; 
                padding: 12px 15px; 
                border-radius: 6px; 
                font-size: 14px;
                line-height: 1.5;
            }
            
            .suna-error { 
                background: #ffebee; 
                color: #c62828; 
                border: 1px solid #ef9a9a;
            }
            
            .suna-success { 
                background: #e8f5e9; 
                color: #2e7d32; 
                border: 1px solid #a5d6a7;
            }
            
            /* 只隐藏默认上传按钮，保留上传栏结构 */
            #plupload-upload-ui .media-button,
            .media-frame-content .upload-button:not(.suna-upload-btn),
            .insert-media-modal .media-button-insert:not(.suna-upload-btn),
            .upload-flash-bypass,
            .mce-ico.mce-i-upload,
            .wp-media-buttons .insert-media-button {
                display: none !important;
            }
            
            /* 上传步骤样式 */
            .suna-upload-steps {
                margin-bottom: 20px;
            }
            
            .suna-steps-container {
                display: flex;
                position: relative;
                margin-bottom: 20px;
            }
            
            .suna-step {
                flex: 1;
                text-align: center;
                position: relative;
                z-index: 2;
            }
            
            .suna-step-icon {
                width: 36px;
                height: 36px;
                border-radius: 50%;
                background: #eee;
                color: white;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 8px;
                font-weight: bold;
                font-size: 16px;
                transition: all 0.3s ease;
            }
            
            .suna-step.active .suna-step-icon {
                background: #3498db;
                box-shadow: 0 0 0 4px rgba(52, 152, 219, 0.2);
            }
            
            .suna-step.completed .suna-step-icon {
                background: #2ecc71;
                box-shadow: 0 0 0 4px rgba(46, 204, 113, 0.2);
            }
            
            .suna-step-label {
                font-size: 13px;
                color: #777;
            }
            
            .suna-step.active .suna-step-label {
                color: #3498db;
                font-weight: 500;
            }
            
            .suna-step.completed .suna-step-label {
                color: #2e7d32;
            }
            
            .suna-progress-line {
                position: absolute;
                top: 18px;
                left: 0;
                right: 0;
                height: 2px;
                background: #eee;
                z-index: 1;
            }
            
            .suna-steps-progress {
                position: absolute;
                top: 0;
                left: 0;
                height: 100%;
                background: #2ecc71;
                transition: width 0.3s;
                width: 0%;
            }
            
            .suna-upload-section {
                display: none;
                animation: fadeIn 0.4s ease;
            }
            
            .suna-upload-section.active {
                display: block;
            }
            
            .suna-fid-input {
                width: 100%;
                padding: 10px;
                margin: 10px 0;
                border: 1px solid #ddd;
                border-radius: 6px;
                box-sizing: border-box;
                font-size: 14px;
                transition: border 0.2s;
            }
            
            .suna-fid-input:focus {
                border-color: #3498db;
                outline: none;
                box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
            }
            
            /* 上传拦截提示样式 */
            .suna-upload-intercept-notice {
                background: #fff3e0;
                border-left: 4px solid #ff9800;
                padding: 15px 12px;
                margin: 15px 0;
                border-radius: 4px;
                font-size: 14px;
                display: flex;
                align-items: center;
                animation: slideUp 0.3s ease;
                z-index: 9998;
                position: relative;
            }
            
            @keyframes slideUp {
                from { transform: translateY(20px); opacity: 0; }
                to { transform: translateY(0); opacity: 1; }
            }
            
            .suna-upload-intercept-notice .dashicons {
                color: #ff9800;
                margin-right: 10px;
                font-size: 20px;
            }
            
            .suna-upload-intercept-notice button {
                margin-left: 15px;
                background: #ff9800;
                color: white;
                border: none;
                padding: 6px 12px;
                border-radius: 4px;
                cursor: pointer;
                transition: background 0.2s;
            }
            
            .suna-upload-intercept-notice button:hover {
                background: #f57c00;
            }
            
            /* 按钮悬停动画效果 */
            .suna-btn {
                position: relative;
                overflow: hidden;
                transition: all 0.3s ease;
            }
            
            .suna-btn::after {
                content: "";
                position: absolute;
                top: 50%;
                left: 50%;
                width: 0;
                height: 0;
                background: rgba(255, 255, 255, 0.2);
                border-radius: 50%;
                transform: translate(-50%, -50%);
                transition: width 0.6s ease, height 0.6s ease;
            }
            
            .suna-btn:hover::after {
                width: 300px;
                height: 300px;
            }
            
            /* 加载动画 */
            .suna-loading {
                display: inline-block;
                width: 20px;
                height: 20px;
                border: 3px solid rgba(255,255,255,.3);
                border-radius: 50%;
                border-top-color: white;
                animation: spin 1s ease-in-out infinite;
                margin-right: 8px;
            }
            
            @keyframes spin {
                to { transform: rotate(360deg); }
            }
            
            /* 媒体库错误提示隐藏 */
            .media-item.suna-cloud-file .upload-error,
            .wp-core-ui .notice-error.suna-cloud-upload-notice {
                display: none !important;
            }
        ');
    }
}

// 添加上传按钮到所有媒体相关页面
add_action('admin_footer', 'suna_add_upload_button', 999);
function suna_add_upload_button() {
    $screen = get_current_screen();
    
    // 对所有管理页面添加上传按钮，确保全覆盖
    if (!$screen || $screen->base !== 'toplevel_page_suna-settings') {
        $fid = get_option('suna_fid', '');
        $api_url = get_option('suna_api_url', 'https://api.snpan.com/opapi');
        $button_position = get_option('suna_button_position', 'default');
        $force_all_uploads = get_option('suna_force_all_uploads', 'on');
        
        // 确定按钮样式类
        $button_classes = ['suna-btn'];
        $is_floating = in_array($button_position, ['top_right', 'bottom_right', 'top_left']);
        
        if ($is_floating) {
            $button_classes[] = 'suna-floating-btn';
            $button_classes[] = $button_position;
        }
        
        ?>
        <!-- 上传按钮 -->
        <button id="suna-upload-btn" class="button button-primary <?php echo implode(' ', $button_classes); ?>">
            <span class="wp-media-buttons-icon dashicons dashicons-cloud-upload"></span>
            <?php echo $is_floating ? '' : '速纳云盘上传'; ?>
        </button>
        
        <div class="suna-modal" id="suna-modal">
            <div class="suna-modal-content">
                <span class="suna-close">&times;</span>
                <h3>上传到速纳云盘</h3>
                
                <!-- 上传步骤指示器 - 简化为2步 -->
                <div class="suna-upload-steps">
                    <div class="suna-steps-container">
                        <div class="suna-progress-line">
                            <div class="suna-steps-progress" id="suna-steps-progress"></div>
                        </div>
                        <div class="suna-step active" id="step-1">
                            <div class="suna-step-icon">1</div>
                            <div class="suna-step-label">验证授权</div>
                        </div>
                        <div class="suna-step" id="step-2">
                            <div class="suna-step-icon">2</div>
                            <div class="suna-step-label">上传文件</div>
                        </div>
                    </div>
                </div>
                
                <!-- 步骤1: 验证授权并获取上传地址（合并步骤） -->
                <div class="suna-upload-section active" id="section-1">
                    <label for="suna-fid">文件夹ID (可选):</label>
                    <input type="text" id="suna-fid" class="suna-fid-input" value="<?php echo esc_attr($fid); ?>" placeholder="输入文件夹ID，留空为根目录">
                    <div id="auth-status" class="suna-message"></div>
                    <button id="verify-auth-btn" class="button button-primary suna-btn">验证授权并获取上传地址</button>
                </div>
                
                <!-- 步骤2: 上传文件 -->
                <div class="suna-upload-section" id="section-2">
                    <label for="suna-file-input">选择文件:</label>
                    <input type="file" id="suna-file-input" accept="*">
                    <div class="suna-progress">
                        <div class="suna-progress-bar">
                            <div class="suna-progress-fill"></div>
                        </div>
                        <div id="suna-progress-text" style="text-align: center; margin-top: 5px;">0%</div>
                    </div>
                    <div id="upload-status" class="suna-message"></div>
                    <button id="start-upload-btn" class="button button-primary suna-btn" disabled>开始上传</button>
                </div>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            var modal = $('#suna-modal');
            var btn = $('#suna-upload-btn');
            var span = $('.suna-close');
            var fileInput = $('#suna-file-input');
            var progress = $('.suna-progress');
            var progressFill = $('.suna-progress-fill');
            var progressText = $('#suna-progress-text');
            var stepsProgress = $('#suna-steps-progress');
            
            // 步骤元素（简化为2步）
            var step1 = $('#step-1');
            var step2 = $('#step-2');
            var section1 = $('#section-1');
            var section2 = $('#section-2');
            
            // 按钮和状态元素
            var verifyAuthBtn = $('#verify-auth-btn');
            var startUploadBtn = $('#start-upload-btn');
            var authStatus = $('#auth-status');
            var uploadStatus = $('#upload-status');
            var sunaFid = $('#suna-fid');
            
            // 存储上传过程中的数据
            var authCode = '';
            var uploadUrl = '';
            var apiBaseUrl = '<?php echo esc_js($api_url); ?>';
            var isFloatingButton = <?php echo $is_floating ? 'true' : 'false'; ?>;
            var forceAllUploads = <?php echo $force_all_uploads === 'on' ? 'true' : 'false'; ?>;
            var uploadInProgress = false; // 新增：防止重复上传
            
            // 将按钮添加到合适的现有位置（非悬浮模式）
            function placeButtonInInterface() {
                if (isFloatingButton) return;
                
                // 尝试将按钮添加到多个标准上传区域
                const insertionPoints = [
                    '#plupload-upload-ui .media-button-group',
                    '.media-toolbar-primary .media-button-group',
                    '#wp-content-media-buttons',
                    '.insert-media-header .media-button-group',
                    '.mce-toolbar .mce-btn-group:last',
                    '.editor-media-upload',
                    '.upload-header',
                    '.media-frame-toolbar',
                    '.attachment-details',
                    '.edit-attachment-frame'
                ];
                
                let inserted = false;
                // 尝试所有可能的插入点
                for (const selector of insertionPoints) {
                    if ($(selector).length) {
                        btn.appendTo(selector);
                        inserted = true;
                        break;
                    }
                }
                
                // 如果所有插入点都失败，添加到媒体库页面的工具栏
                if (!inserted) {
                    if ($('.media-toolbar').length) {
                        btn.prependTo('.media-toolbar');
                    } else if ($('#wpadminbar').length) {
                        // 最后尝试添加到页面顶部工具栏
                        $('<div class="ab-item"></div>').append(btn).appendTo('#wpadminbar .quicklinks ul:first');
                    } else {
                        // 终极方案：添加到body
                        btn.css({
                            position: 'fixed',
                            top: '20px',
                            right: '20px',
                            zIndex: '9999'
                        }).appendTo('body');
                    }
                }
            }
            
            // 初始化按钮位置
            placeButtonInInterface();
            
            // 显示模态框
            btn.click(function(e) {
                e.preventDefault();
                modal.show();
                resetUploadState();
            });
            
            // 关闭模态框
            span.click(function() {
                modal.hide();
            });
            
            $(window).click(function(event) {
                if (event.target == modal[0]) {
                    modal.hide();
                }
            });
            
            // 文件选择变化时启用上传按钮
            fileInput.change(function(e) {
                startUploadBtn.prop('disabled', this.files.length === 0 || uploadInProgress);
                if (this.files.length > 0) {
                    showMessage(uploadStatus, '已选择文件: ' + this.files[0].name, 'success');
                }
            });
            
            // 验证授权并获取上传地址（合并步骤）
            verifyAuthBtn.click(function() {
                if (uploadInProgress) return;
                
                showMessage(authStatus, '正在验证授权并获取上传地址...', 'info');
                verifyAuthBtn.prop('disabled', true).html('<span class="suna-loading"></span>处理中...');
                
                var fid = sunaFid.val().trim();
                
                $.post(ajaxurl, {
                    action: 'suna_get_auth_and_upload_url',
                    fid: fid
                }).done(function(response) {
                    verifyAuthBtn.html('验证授权并获取上传地址');
                    
                    if (!response.success) {
                        showMessage(authStatus, response.data, 'error');
                        verifyAuthBtn.prop('disabled', false);
                        return;
                    }
                    
                    // 直接获取授权码和上传地址
                    authCode = response.data.authcode;
                    uploadUrl = response.data.upload_url;
                    showMessage(authStatus, '授权验证及上传地址获取成功', 'success');
                    
                    // 更新步骤指示器
                    step1.removeClass('active').addClass('completed');
                    step2.addClass('active');
                    stepsProgress.css('width', '50%');
                    
                    // 切换到第二步
                    setTimeout(function() {
                        section1.removeClass('active');
                        section2.addClass('active');
                    }, 500);
                    
                }).fail(function() {
                    verifyAuthBtn.html('验证授权并获取上传地址');
                    showMessage(authStatus, '处理失败，请重试', 'error');
                    verifyAuthBtn.prop('disabled', false);
                });
            });
            
            // 开始上传
            startUploadBtn.click(function() {
                if (uploadInProgress) return;
                
                var file = fileInput[0].files[0];
                if (!file) {
                    showMessage(uploadStatus, '请选择要上传的文件', 'error');
                    return;
                }
                if (!uploadUrl) {
                    showMessage(uploadStatus, '请先获取上传地址', 'error');
                    return;
                }
                
                uploadInProgress = true;
                uploadFile(file);
            });
            
            // 上传文件函数
            function uploadFile(file) {
                showMessage(uploadStatus, '正在上传文件...', 'info');
                startUploadBtn.prop('disabled', true).html('<span class="suna-loading"></span>上传中...');
                progress.show();
                progressFill.css('width', '0%');
                progressText.text('0%');
                
                var formData = new FormData();
                formData.append('file', file);
                
                // 使用XMLHttpRequest支持进度条
                var xhr = new XMLHttpRequest();
                xhr.open('POST', uploadUrl, true);
                
                // 监听进度事件
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        var percent = Math.round((e.loaded / e.total) * 100);
                        progressFill.css('width', percent + '%');
                        progressText.text(percent + '%');
                    }
                });
                
                // 上传完成处理
                xhr.addEventListener('load', function() {
                    uploadInProgress = false;
                    startUploadBtn.html('开始上传');
                    
                    try {
                        var responseText = xhr.responseText || '{"code":500,"msg":"空响应"}';
                        var result = JSON.parse(responseText);
                        
                        var errorMessages = {
                            255: "权限验证失败，请检查API密钥和AID是否正确",
                            400: "请求参数错误",
                            401: "未授权访问",
                            403: "禁止访问",
                            404: "上传地址不存在",
                            500: "服务器内部错误"
                        };
                        
                        if (xhr.status === 200) {
                            if (result.code == 200 && result.data) {
                                var fileUrl = result.data;
                                if (typeof fileUrl === 'object' && fileUrl.url) {
                                    fileUrl = fileUrl.url;
                                }
                                
                                if (typeof fileUrl === 'string') {
                                    if (fileUrl.startsWith("`")) fileUrl = fileUrl.substring(1);
                                    if (fileUrl.endsWith("`")) fileUrl = fileUrl.substring(0, fileUrl.length - 1);
                                }
                                
                                // 更新步骤指示器为完成状态
                                step2.removeClass('active').addClass('completed');
                                stepsProgress.css('width', '100%');
                                
                                // 添加到媒体库并插入编辑器
                                addToMediaLibrary(fileUrl, file.name, file.type);
                            } else {
                                var errorMsg = errorMessages[result.code] || result.msg || '未知错误';
                                showMessage(uploadStatus, '上传失败: ' + errorMsg + ' (错误码: ' + result.code + ')', 'error');
                                startUploadBtn.prop('disabled', false);
                            }
                        } else {
                            var errorMsg = errorMessages[xhr.status] || xhr.statusText;
                            showMessage(uploadStatus, '上传失败: HTTP ' + xhr.status + ' - ' + errorMsg, 'error');
                            startUploadBtn.prop('disabled', false);
                        }
                    } catch (e) {
                        showMessage(uploadStatus, '上传响应解析错误: ' + e.message, 'error');
                        console.error('上传响应解析错误:', e, xhr.responseText);
                        startUploadBtn.prop('disabled', false);
                    }
                });
                
                // 上传错误处理
                xhr.addEventListener('error', function() {
                    uploadInProgress = false;
                    startUploadBtn.html('开始上传');
                    showMessage(uploadStatus, '网络错误，上传请求失败', 'error');
                    startUploadBtn.prop('disabled', false);
                });
                
                xhr.timeout = 60000;
                xhr.ontimeout = function() {
                    uploadInProgress = false;
                    startUploadBtn.html('开始上传');
                    showMessage(uploadStatus, '上传超时，请重试', 'error');
                    startUploadBtn.prop('disabled', false);
                };
                
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                xhr.send(formData);
            }
            
            // 显示消息函数
            function showMessage(element, text, type) {
                element.text(text);
                element.removeClass('suna-error suna-success');
                
                if (type === 'error') {
                    element.addClass('suna-error');
                } else if (type === 'success') {
                    element.addClass('suna-success');
                }
            }
            
            // 重置上传状态
            function resetUploadState() {
                uploadInProgress = false;
                authCode = '';
                uploadUrl = '';
                fileInput.val('');
                progress.hide();
                progressFill.css('width', '0%');
                progressText.text('0%');
                startUploadBtn.prop('disabled', true).html('开始上传');
                
                // 重置步骤
                $('.suna-step').removeClass('active completed');
                step1.addClass('active');
                stepsProgress.css('width', '0%');
                
                // 重置消息
                $('.suna-message').text('').removeClass('suna-error suna-success');
                
                // 显示第一步
                $('.suna-upload-section').removeClass('active');
                section1.addClass('active');
                
                // 重置按钮状态
                verifyAuthBtn.prop('disabled', false).html('验证授权并获取上传地址');
            }
            
            // 添加到媒体库并插入编辑器
            function addToMediaLibrary(url, filename, filetype) {
                showMessage(uploadStatus, '正在添加到媒体库...', 'info');
                
                $.post(ajaxurl, {
                    action: 'suna_add_media',
                    url: url,
                    filename: filename,
                    filetype: filetype
                }).done(function(response) {
                    if (response.success) {
                        showMessage(uploadStatus, '上传成功！文件已添加到媒体库', 'success');
                        
                        // 插入到编辑器
                        if (typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                            var ext = filename.split('.').pop().toLowerCase();
                            var imageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
                            var videoExts = ['mp4', 'webm', 'ogg', 'mov', 'avi'];
                            var audioExts = ['mp3', 'wav', 'ogg', 'flac'];
                            
                            let content = '';
                            if (imageExts.includes(ext)) {
                                content = '<img src="' + url + '" alt="' + filename + '" style="max-width:100%;" />';
                            } else if (videoExts.includes(ext)) {
                                content = '<video src="' + url + '" controls style="max-width:100%;"></video>';
                            } else if (audioExts.includes(ext)) {
                                content = '<audio src="' + url + '" controls></audio>';
                            } else {
                                content = '<a href="' + url + '">' + filename + '</a>';
                            }
                            
                            tinyMCE.activeEditor.execCommand('mceInsertContent', false, content);
                        }
                        
                        // 刷新媒体库列表
                        if (typeof wp.media !== 'undefined' && wp.media.frame) {
                            wp.media.frame.library.reload(true);
                        }
                        
                        // 3秒后关闭模态框
                        setTimeout(function() {
                            modal.hide();
                        }, 3000);
                    } else {
                        showMessage(uploadStatus, '添加到媒体库失败: ' + response.data, 'error');
                        startUploadBtn.prop('disabled', false);
                    }
                }).fail(function() {
                    showMessage(uploadStatus, '添加到媒体库请求失败', 'error');
                    startUploadBtn.prop('disabled', false);
                });
            }
            
            // 增强的上传拦截功能
            function interceptDefaultUpload() {
                if (!forceAllUploads) return;
                
                // 防止重复绑定事件
                if (window.sunaEventsBound) return;
                window.sunaEventsBound = true;
                
                // 拦截拖放上传
                $(document).on('dragover drop', function(e) {
                    // 忽略速纳模态框内的拖放
                    if ($(e.target).closest('.suna-modal, #suna-upload-btn, #suna-upload-btn-editor').length) return;
                    
                    e.preventDefault();
                    e.stopPropagation();
                    
                    if (e.type === 'dragover') {
                        showUploadInterceptNotice();
                    }
                });
                
                // 拦截文件选择
                $(document).on('click', '.upload_file, .media-modal-icon, .upload_button, .add_media', function(e) {
                    // 排除速纳的上传按钮
                    if ($(this).closest('#suna-upload-btn, #suna-upload-btn-editor, .suna-modal').length) {
                        return; // 允许速纳按钮的正常操作
                    }
                    
                    e.preventDefault();
                    e.stopPropagation();
                    showUploadInterceptNotice();
                    return false;
                });
                
                // 拦截媒体库上传按钮
                $(document).on('click', '.media-button-insert, .insert-media-button, .mce_i_upload', function(e) {
                    // 排除速纳的上传按钮
                    if ($(this).closest('#suna-upload-btn, #suna-upload-btn-editor, .suna-modal').length) {
                        return; // 允许速纳按钮的正常操作
                    }
                    
                    e.preventDefault();
                    e.stopPropagation();
                    showUploadInterceptNotice();
                    return false;
                });
                
                // 拦截编辑器中的上传按钮
                $(document).on('click', '.mce-i-upload, .wp-media-buttons button', function(e) {
                    if (!$(this).closest('#suna-upload-btn-editor, #suna-upload-btn').length) {
                        e.preventDefault();
                        e.stopPropagation();
                        showUploadInterceptNotice();
                        return false;
                    }
                });
                
                // 拦截各种可能的上传表单提交
                $(document).on('submit', 'form[enctype="multipart/form-data"]', function(e) {
                    // 检查表单是否包含文件上传字段
                    if ($(this).find('input[type="file"]').length && 
                        !$(this).closest('.suna-modal').length) {
                        e.preventDefault();
                        e.stopPropagation();
                        showUploadInterceptNotice();
                        return false;
                    }
                });
                
                // 拦截XMLHttpRequest上传
                (function(open) {
                    XMLHttpRequest.prototype.open = function(method, url) {
                        // 不拦截速纳自身的上传请求
                        if (url.includes('suna_add_media') || url.includes('suna_get_auth_and_upload_url')) {
                            open.apply(this, arguments);
                            return;
                        }
                        
                        if (method === 'POST' && (url.indexOf('async-upload.php') !== -1 || 
                            url.indexOf('upload-attachment') !== -1 || 
                            url.indexOf('media-upload.php') !== -1)) {
                            this.addEventListener('readystatechange', function() {
                                if (this.readyState === 4) {
                                    try {
                                        var response = JSON.parse(this.responseText);
                                        if (!response.success) {
                                            showUploadInterceptNotice();
                                        }
                                    } catch (e) {
                                        showUploadInterceptNotice();
                                    }
                                }
                            }, false);
                        }
                        open.apply(this, arguments);
                    };
                })(XMLHttpRequest.prototype.open);
                
                // 监测文件输入框变化
                $(document).on('change', 'input[type="file"]', function(e) {
                    if ($(this).closest('#suna-file-input, .suna-modal').length) return;
                    
                    if (this.files && this.files.length > 0) {
                        e.preventDefault();
                        e.stopPropagation();
                        // 清空选择的文件
                        $(this).val('');
                        showUploadInterceptNotice();
                        return false;
                    }
                });
            }
            
            // 显示上传拦截提示
            function showUploadInterceptNotice() {
                // 如果模态框已经打开，不显示提示
                if (modal.is(':visible')) return;
                
                // 如果已经显示了提示，不再重复显示
                if ($('.suna-upload-intercept-notice').length) {
                    return;
                }
                
                var notice = $('<div class="suna-upload-intercept-notice">' +
                    '<span class="dashicons dashicons-info"></span>' +
                    '<span>文件上传已被速纳云盘接管，请使用速纳云盘上传功能</span>' +
                    '<button id="open-suna-upload">打开速纳上传</button>' +
                '</div>');
                
                // 根据当前界面选择合适的位置显示提示
                var targetContainer = $('.media-frame-content, #wpbody-content, .editor-block-list__layout, .upload-php, .post-php, .page-php').first();
                if (targetContainer.length) {
                    targetContainer.prepend(notice);
                } else {
                    $('body').append(notice);
                }
                
                notice.find('#open-suna-upload').click(function() {
                    btn.click();
                    notice.remove();
                });
                
                // 点击其他区域关闭提示
                $(document).on('click', function(e) {
                    if (!$(e.target).closest('.suna-upload-intercept-notice').length) {
                        notice.remove();
                    }
                });
                
                setTimeout(function() {
                    notice.fadeOut(300, function() {
                        $(this).remove();
                    });
                }, 8000);
            }
            
            // 初始化上传拦截
            interceptDefaultUpload();
            
            // 页面加载完成后检查是否有上传表单并替换
            replaceDefaultUploadForms();
            
            // 替换默认上传表单
            function replaceDefaultUploadForms() {
                if (!forceAllUploads) return;
                
                // 查找所有文件上传表单并替换其行为
                $('form[enctype="multipart/form-data"]').each(function() {
                    var $form = $(this);
                    // 跳过速纳自身的表单
                    if ($form.closest('.suna-modal').length) return;
                    
                    // 检查表单是否包含文件上传字段
                    if ($form.find('input[type="file"]').length) {
                        // 保存原始提交处理
                        var originalSubmit = $form.attr('onsubmit');
                        $form.attr('onsubmit', 'return false;');
                        
                        // 添加提交事件处理
                        $form.submit(function(e) {
                            e.preventDefault();
                            showUploadInterceptNotice();
                            return false;
                        });
                    }
                });
            }
            
            // 修复媒体库中的错误提示显示
            function fixMediaLibraryErrors() {
                // 定期检查并修复媒体库中的错误显示
                setInterval(function() {
                    // 标记云文件的媒体项
                    $('[data-attachment-id]').each(function() {
                        var id = $(this).data('attachment-id');
                        if (typeof sunaCloudFiles !== 'undefined' && sunaCloudFiles.includes(id)) {
                            $(this).closest('.media-item, .attachment').addClass('suna-cloud-file');
                        }
                    });
                    
                    // 移除云文件的错误提示
                    $('.media-item.suna-cloud-file .upload-error, .attachment.suna-cloud-file .upload-error').hide();
                }, 1000);
            }
            
            // 启动媒体库错误修复
            fixMediaLibraryErrors();
        });
        </script>
        <?php
    }
}

// 在编辑器添加上传按钮
add_action('media_buttons', 'suna_add_editor_upload_button', 11);
function suna_add_editor_upload_button() {
    $button_position = get_option('suna_button_position', 'default');
    // 只有在默认位置时才在编辑器添加额外按钮
    if ($button_position === 'default' || true) { // 强制在编辑器显示按钮
        echo '<button id="suna-upload-btn-editor" class="button button-primary suna-btn">
                
                <span class="wp-media-buttons-icon dashicons dashicons-cloud-upload"></span>
                速纳云盘上传
              </button>';
              
        echo '<script>
        jQuery(document).ready(function($) {
            $("#suna-upload-btn-editor").click(function(e) {
                e.preventDefault();
                $("#suna-upload-btn").click();
            });
        });
        </script>';
    }
}

// 完全替换WordPress的上传处理 - 只保留一个核心拦截点
add_filter('wp_handle_upload_prefilter', 'suna_block_default_upload', 100);
function suna_block_default_upload($file) {
    // 检查是否已经是云上传的文件，避免重复处理
    if (!empty($file['tmp_name']) && strpos($file['tmp_name'], 'suna-cloud') !== false) {
        return $file;
    }
    
    $aid = get_option('suna_aid');
    $key = get_option('suna_key');
    $force_all_uploads = get_option('suna_force_all_uploads', 'on');
    
    if ($force_all_uploads === 'on' && !empty($aid) && !empty($key)) {
        // 直接处理上传而不是仅返回错误
        $processed_file = suna_handle_upload_internally($file);
        
        // 确保成功上传时清除所有错误状态
        if (!empty($processed_file['url']) && strpos($processed_file['tmp_name'], 'suna-cloud') !== false) {
            $processed_file['error'] = UPLOAD_ERR_OK;
            
            // 清除上传目录错误
            add_filter('upload_dir', function($uploads) {
                $uploads['error'] = '';
                return $uploads;
            }, 999);
        }
        
        return $processed_file;
    }
    return $file;
}


// 统一处理URL的函数
function suna_process_file_url($fileUrl) {
    // 确保URL是字符串
    if (is_array($fileUrl)) {
        // 检查常见的URL字段
        if (isset($fileUrl['url'])) {
            $fileUrl = $fileUrl['url'];
        } elseif (isset($fileUrl['data'])) {
            $fileUrl = $fileUrl['data'];
        } else {
            // 转换数组为JSON以便调试
            $fileUrl = json_encode($fileUrl);
        }
    }
    
    // 清理可能的引号
    if (is_string($fileUrl)) {
        // 移除可能的反引号
        $fileUrl = trim($fileUrl, "`'\"");
        
        // 验证URL格式
        if (filter_var($fileUrl, FILTER_VALIDATE_URL) === false) {
            // 尝试从字符串中提取URL
            if (preg_match('/https?:\/\/[^\s]+/', $fileUrl, $matches)) {
                $fileUrl = $matches[0];
            }
        }
    }
    
    return $fileUrl;
}

// 内部处理上传文件
function suna_handle_upload_internally($file) {
    // 防止重复处理
    static $processing = false;
    if ($processing) {
        return $file;
    }
    
    // 如果是有效的文件，尝试通过速纳上传
    if ($file['error'] === UPLOAD_ERR_OK) {
        $processing = true;
        
        $aid = get_option('suna_aid');
        $key = get_option('suna_key');
        $fid = get_option('suna_fid', '');
        $api_url = get_option('suna_api_url', 'https://api.snpan.com/opapi');
        
        // 计算文件MD5
        $file_md5 = md5_file($file['tmp_name']);
        
        // 获取授权码
        $authResponse = wp_remote_get($api_url . '/GetAuthCode?aid=' . urlencode($aid) . '&key=' . urlencode($key) . '&md5=' . $file_md5, array(
            'sslverify' => false,
            'timeout' => 30,
            'headers' => array(
                'Origin' => site_url(),
                'X-Requested-With' => 'XMLHttpRequest'
            )
        ));
        
        if (is_wp_error($authResponse)) {
            $file['error'] = '获取授权码失败: ' . $authResponse->get_error_message();
            $processing = false;
            return $file;
        }
        
        $authBody = json_decode(wp_remote_retrieve_body($authResponse), true);
        if (!$authBody || $authBody['code'] != 200 || empty($authBody['data'])) {
            $errorMsg = $authBody['msg'] ?? '未知错误';
            $file['error'] = "授权失败: $errorMsg";
            $processing = false;
            return $file;
        }
        
        // 获取上传地址，包含文件夹ID
        $uploadUrlParams = 'authcode=' . urlencode($authBody['data']);
        if (!empty($fid)) {
            $uploadUrlParams .= '&fid=' . urlencode($fid);
        }
        
        $uploadUrlResponse = wp_remote_get($api_url . '/Getuploads?' . $uploadUrlParams, array(
            'sslverify' => false,
            'timeout' => 30,
            'headers' => array(
                'Origin' => site_url(),
                'X-Requested-With' => 'XMLHttpRequest'
            )
        ));
        
        if (is_wp_error($uploadUrlResponse)) {
            $file['error'] = '获取上传地址失败: ' . $uploadUrlResponse->get_error_message();
            $processing = false;
            return $file;
        }
        
        $uploadUrlBody = json_decode(wp_remote_retrieve_body($uploadUrlResponse), true);
        if (!$uploadUrlBody || $uploadUrlBody['code'] != 200 || empty($uploadUrlBody['data']['url']) || empty($uploadUrlBody['data']['query'])) {
            $errorMsg = $uploadUrlBody['msg'] ?? '未知错误';
            $file['error'] = "获取上传地址失败: $errorMsg";
            $processing = false;
            return $file;
        }
        
        $uploadUrl = $uploadUrlBody['data']['url'] . '/upload?' . $uploadUrlBody['data']['query'];
        
        // 上传文件
        $tmp_file = $file['tmp_name'];
        
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $uploadUrl,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => array('file' => new CURLFile($tmp_file, $file['type'], $file['name'])),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => array(
                'X-Requested-With: XMLHttpRequest',
                'Origin: ' . site_url()
            ),
            CURLOPT_TIMEOUT => 60
        ));
        
        $response = curl_exec($curl);
        
        if(curl_errno($curl)) {
            $curlError = curl_error($curl);
            curl_close($curl);
            $file['error'] = '文件上传失败: ' . $curlError;
            $processing = false;
            return $file;
        }
        
        curl_close($curl);
        
        if(empty($response)) {
            $file['error'] = '未收到服务器响应';
            $processing = false;
            return $file;
        }
        
        $result = json_decode($response, true);
        
        if(json_last_error() !== JSON_ERROR_NONE) {
            $file['error'] = '响应解析失败: ' . json_last_error_msg();
            $processing = false;
            return $file;
        }
        
        if ($result && $result['code'] == 200 && $result['data']) {
            // 使用统一的URL处理函数
            $fileUrl = suna_process_file_url($result['data']);
            
            // 创建媒体库条目
            $attachment = array(
                'post_mime_type' => $file['type'],
                'post_title' => sanitize_text_field(pathinfo($file['name'], PATHINFO_FILENAME)),
                'post_content' => '',
                'post_status' => 'inherit',
                'guid' => $fileUrl // 直接设置guid为云URL
            );
            
            $attach_id = wp_insert_attachment($attachment, '', 0);
            update_post_meta($attach_id, '_suna_cloud_url', $fileUrl);
            update_post_meta($attach_id, '_suna_cloud_file', true);
            
            // 只设置url，不修改file路径
            $file['url'] = $fileUrl;
            $file['error'] = UPLOAD_ERR_OK;
            
            // 标记为已处理，避免重复
            $file['tmp_name'] = 'suna-cloud-' . $file['tmp_name'];
            
            // 存储成功标记用于错误抑制
            set_transient('suna_cloud_upload_success_' . $attach_id, true, 60);
            
            $processing = false;
            return $file;
        } else {
            $errorMsg = $result['msg'] ?? '未知错误';
            $file['error'] = "上传失败: $errorMsg";
            $processing = false;
            return $file;
        }
    }
    
    $processing = false;
    return $file;
}

// 处理附件添加 - 修改为仅处理未被suna_block_default_upload处理的文件
add_action('add_attachment', 'suna_handle_attachment_addition', 10, 1);
function suna_handle_attachment_addition($attachment_id) {
    // 防止重复处理
    static $processing = false;
    if ($processing) {
        return;
    }
    
    $aid = get_option('suna_aid');
    $key = get_option('suna_key');
    $force_all_uploads = get_option('suna_force_all_uploads', 'on');
    
    // 检查是否已经是云文件
    $is_cloud_file = get_post_meta($attachment_id, '_suna_cloud_file', true);
    
    // 仅处理非云文件，并且force_all_uploads开启
    if ($force_all_uploads === 'on' && !empty($aid) && !empty($key) && !$is_cloud_file) {
        $processing = true;
        
        $attachment = get_post($attachment_id);
        $file_path = get_attached_file($attachment_id);
        
        // 检查文件是否存在且未被处理过
        if ($file_path && file_exists($file_path) && strpos($file_path, 'suna-cloud') === false) {
            // 创建模拟的文件数组
            $file = array(
                'name' => $attachment->post_title,
                'type' => $attachment->post_mime_type,
                'tmp_name' => $file_path,
                'error' => UPLOAD_ERR_OK,
                'size' => filesize($file_path)
            );
            
            // 通过速纳上传
            $result = suna_handle_upload_internally($file);
            
            if ($result['error'] === UPLOAD_ERR_OK) {
                // 更新附件的URL和GUID
                $attachment_data = array(
                    'ID' => $attachment_id,
                    'guid' => $result['url']
                );
                wp_update_post($attachment_data);
                
                update_post_meta($attachment_id, '_suna_cloud_url', $result['url']);
                update_post_meta($attachment_id, '_suna_cloud_file', true);
                
                // 存储成功标记
                set_transient('suna_cloud_upload_success_' . $attachment_id, true, 60);
                
                // 删除本地文件
                @unlink($file_path);
            }
        }
        
        $processing = false;
    }
}

// 合并验证授权和获取上传地址的接口
add_action('wp_ajax_suna_get_auth_and_upload_url', 'suna_ajax_get_auth_and_upload_url');
function suna_ajax_get_auth_and_upload_url() {
    $aid = get_option('suna_aid');
    $key = get_option('suna_key');
    $fid = $_POST['fid'] ?? '';
    $api_url = get_option('suna_api_url', 'https://api.snpan.com/opapi');
    
    if (empty($aid) || empty($key)) {
        wp_send_json_error('请先配置AID和API Key');
    }
    
    // 1. 获取授权码
    $authResponse = wp_remote_get($api_url . '/GetAuthCode?aid=' . urlencode($aid) . '&key=' . urlencode($key), array(
        'sslverify' => false,
        'timeout' => 30
    ));
    if (is_wp_error($authResponse)) {
        wp_send_json_error('获取授权码失败: ' . $authResponse->get_error_message());
    }
    $authBody = json_decode(wp_remote_retrieve_body($authResponse), true);
    if (!$authBody || $authBody['code'] != 200 || empty($authBody['data'])) {
        $errorMsg = $authBody['msg'] ?? '未知错误';
        wp_send_json_error("授权失败: $errorMsg");
    }
    $authcode = $authBody['data'];
    
    // 2. 获取上传地址
    $params = 'authcode=' . urlencode($authcode);
    if (!empty($fid)) {
        $params .= '&fid=' . urlencode($fid);
    }
    $uploadUrlResponse = wp_remote_get($api_url . '/Getuploads?' . $params, array(
        'sslverify' => false,
        'timeout' => 30
    ));
    if (is_wp_error($uploadUrlResponse)) {
        wp_send_json_error('获取上传地址失败: ' . $uploadUrlResponse->get_error_message());
    }
    $uploadUrlBody = json_decode(wp_remote_retrieve_body($uploadUrlResponse), true);
    if (!$uploadUrlBody || $uploadUrlBody['code'] != 200 || empty($uploadUrlBody['data']['url']) || empty($uploadUrlBody['data']['query'])) {
        $errorMsg = $uploadUrlBody['msg'] ?? '未知错误';
        wp_send_json_error("获取上传地址失败: $errorMsg");
    }
    $uploadUrl = $uploadUrlBody['data']['url'] . '/upload?' . $uploadUrlBody['data']['query'];
    
    wp_send_json_success([
        'authcode' => $authcode,
        'upload_url' => $uploadUrl
    ]);
}

// AJAX添加到媒体库
add_action('wp_ajax_suna_add_media', 'suna_ajax_add_media');
function suna_ajax_add_media() {
    $url = $_POST['url'] ?? '';
    $filename = $_POST['filename'] ?? 'suna-upload';
    $filetype = $_POST['filetype'] ?? 'application/octet-stream';
    
    if (empty($url)) {
        wp_send_json_error('文件URL为空');
    }
    
    // 处理URL
    $url = suna_process_file_url($url);
    
    // 创建媒体库条目
    $attachment = array(
        'post_mime_type' => $filetype,
        'post_title' => sanitize_text_field(pathinfo($filename, PATHINFO_FILENAME)),
        'post_content' => '',
        'post_status' => 'inherit',
        'guid' => $url
    );
    
    $attach_id = wp_insert_attachment($attachment, '', 0);
    update_post_meta($attach_id, '_suna_cloud_url', $url);
    update_post_meta($attach_id, '_suna_cloud_file', true);
    
    // 存储成功标记
    set_transient('suna_cloud_upload_success_' . $attach_id, true, 60);
    
    if (strpos($filetype, 'image/') === 0) {
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $attach_data = array(
            'width' => 0,
            'height' => 0,
            'file' => basename($url),
            'sizes' => array(),
            'image_meta' => array()
        );
        wp_update_attachment_metadata($attach_id, $attach_data);
    }
    
    wp_send_json_success();
}

// 修复URL显示问题
add_filter('wp_get_attachment_url', 'suna_custom_attachment_url', 999, 2);
function suna_custom_attachment_url($url, $attachment_id) {
    $cloud_url = get_post_meta($attachment_id, '_suna_cloud_url', true);
    if (!empty($cloud_url)) {
        // 处理URL
        $cloud_url = suna_process_file_url($cloud_url);
        // 检查是否已拼接，如果是则直接返回云URL
        if (strpos($url, $cloud_url) !== false) {
            return $cloud_url;
        }
        return $cloud_url;
    }
    return $url;
}

// 修复媒体库列表中的URL
add_filter('wp_prepare_attachment_for_js', 'suna_prepare_attachment_for_js', 999, 3);
function suna_prepare_attachment_for_js($response, $attachment, $meta) {
    $cloud_url = get_post_meta($attachment->ID, '_suna_cloud_url', true);
    if (!empty($cloud_url)) {
        // 处理URL
        $cloud_url = suna_process_file_url($cloud_url);
        $response['url'] = $cloud_url;
        if (isset($response['sizes'])) {
            foreach ($response['sizes'] as $size => $size_data) {
                $response['sizes'][$size]['url'] = $cloud_url;
            }
        }
        // 修复guid显示
        $response['guid'] = $cloud_url;
        // 确保状态显示为成功
        $response['uploadedTo'] = true;
        $response['status'] = 'inherit';
    }
    return $response;
}

// 确保前端也使用云存储URL
add_filter('the_content', 'suna_replace_attachment_urls_in_content', 999);
function suna_replace_attachment_urls_in_content($content) {
    // 查找所有附件URL并替换为云存储URL
    preg_match_all('/wp-content\/uploads\/[^"\']+/', $content, $matches);
    
    if (!empty($matches[0])) {
        foreach ($matches[0] as $local_url) {
            // 查找对应的附件
            $attachment_id = attachment_url_to_postid(site_url('/' . $local_url));
            if ($attachment_id) {
                $cloud_url = get_post_meta($attachment_id, '_suna_cloud_url', true);
                if (!empty($cloud_url)) {
                    // 处理URL
                    $cloud_url = suna_process_file_url($cloud_url);
                    // 移除本地路径部分再替换
                    $content = str_replace(site_url('/wp-content/uploads/') . $cloud_url, $cloud_url, $content);
                    $content = str_replace($local_url, $cloud_url, $content);
                }
            }
        }
    }
    
    // 额外检查是否有错误拼接的URL并修复
    $upload_dir = wp_upload_dir();
    $upload_base_url = trailingslashit($upload_dir['baseurl']);
    $content = str_replace($upload_base_url . 'https://', 'https://', $content);
    $content = str_replace($upload_base_url . 'http://', 'http://', $content);
    
    return $content;
}

// 增强错误消息抑制
add_action('admin_notices', 'suna_suppress_upload_errors', 1);
function suna_suppress_upload_errors() {
    // 处理URL参数中的错误消息
    if (isset($_GET['message']) && in_array($_GET['message'], array(1, 2, 3, 4, 5, 6, 7, 8))) {
        if (isset($_REQUEST['attachment_id'])) {
            $attach_id = intval($_REQUEST['attachment_id']);
            // 双重验证：元数据和临时标记
            if (get_post_meta($attach_id, '_suna_cloud_file', true) || 
                get_transient('suna_cloud_upload_success_' . $attach_id)) {
                remove_all_actions('admin_notices', 10);
                // 清除临时标记
                delete_transient('suna_cloud_upload_success_' . $attach_id);
                
                // 显示成功消息替代
                echo '<div class="notice notice-success is-dismissible">
                    <p>文件已成功上传到速纳云盘</p>
                </div>';
            }
        }
    }
    
    // 处理媒体库中的错误提示
    add_filter('admin_post_thumbnail_html', function($html) {
        if (strpos($html, '上传失败') !== false && isset($_REQUEST['attachment_id'])) {
            $attach_id = intval($_REQUEST['attachment_id']);
            if (get_post_meta($attach_id, '_suna_cloud_file', true)) {
                return str_replace('上传失败', '上传成功', $html);
            }
        }
        return $html;
    });
}

// 提供云文件ID列表给前端
add_action('admin_footer', 'suna_localize_cloud_files');
function suna_localize_cloud_files() {
    $cloud_files = get_posts(array(
        'post_type' => 'attachment',
        'meta_key' => '_suna_cloud_file',
        'meta_value' => true,
        'posts_per_page' => -1,
        'fields' => 'ids'
    ));
    echo '<script>var sunaCloudFiles = ' . json_encode($cloud_files) . ';</script>';
}
    